# encoding:utf-8
"""
@file = user_manage
@author = zouju
@create_time = 2023-09-12- 15:30
"""
from django.contrib.auth.hashers import make_password, check_password
from django.shortcuts import render
from rest_framework.decorators import api_view

from common.API import res_josn_data
from common.API.log import exec_log
from common.authentication.jwt_auth import jwt_login_required
from common.layuiview.layuiviewsets import ModelViewSetLayui
from system_manage.models import User, Role, Department
from system_manage.serializers import UserModelSerializer, RoleQueryModelSerializer, DeptQueryModelSerializer


def user_manage_page(request):
    return render(request, 'sys_manage/user_manage/user_main.html')


# @api_view(['GET'])

def user_add_page(request):
    return render(request, 'sys_manage/user_manage/user_add.html')


def user_role_edit_page(request):
    return render(request, 'sys_manage/user_manage/user_role_edit.html')


def user_setting_page(request):
    return render(request, 'sys_manage/user_manage/user_setting.html')


def user_password_page(request):
    return render(request, 'sys_manage/user_manage/user_password.html')


def password_reset_page(request):
    return render(request, 'sys_manage/user_manage/password_reset.html')


@api_view(['POST'])
@jwt_login_required
def user_setting_save(request):
    post_data = request.POST.dict()
    id_number = post_data['id_number']
    print('post_data', post_data)
    User.objects.filter(id_number=post_data['id_number']).update(**post_data)
    exec_log(request, is_access=True, desc=f'账号:{id_number} 更新成功')
    return res_josn_data.success_api('更新成功')


@api_view(['POST'])
@jwt_login_required
def user_password_save(request):
    old_password = request.POST['old_password']
    new_password = request.POST['new_password']
    again_password = request.POST['again_password']
    user_obj = User.objects.filter(id_number=request.user).first()
    if not check_password(old_password, user_obj.id_password):
        return res_josn_data.fail_api(msg='原密码错误')
    elif new_password != again_password:
        return res_josn_data.fail_api(msg='两次密码不一致')
    else:
        user_obj.id_password = make_password(new_password, salt=None, hasher='default')
        user_obj.save()
        exec_log(request, is_access=True, desc=f'账号:{user_obj.id_number} 密码已修改')
        return res_josn_data.success_api(msg='修改成功')


@api_view(['POST'])
@jwt_login_required
def password_reset(request):
    post_data = request.POST
    print('post_data', post_data)
    user = User.objects.get(id=post_data['id'])
    user.id_password = make_password(post_data['id_password'], salt=None, hasher='default')
    user.save()
    exec_log(request, is_access=True, desc=f'账号:{post_data["id_number"]} 密码已重置')
    return res_josn_data.success_api(msg='密码重置成功')


@api_view(['POST'])
@jwt_login_required
def user_info_query(request):
    post_data = request.POST
    id_number = post_data['id_number']
    dept = Department.objects.values('id', 'name').filter(enable=1)
    user = User.objects.get(id_number=id_number)
    serializer = UserModelSerializer(instance=user)
    data_dict = serializer.data
    data_dict['dept_info'] = list(dept)
    return res_josn_data.user_info(data=data_dict, count=1)


@api_view(['POST'])
@jwt_login_required
def user_role_query(request):
    role_data = Role.objects.filter(enable=1).all()
    serializer = RoleQueryModelSerializer(instance=role_data, many=True)
    return res_josn_data.table_api(data=serializer.data, count=len(role_data))


@api_view(['POST'])
@jwt_login_required
def user_dept_query(request):
    role_data = Department.objects.filter(enable=1).all()
    serializer = DeptQueryModelSerializer(instance=role_data, many=True)
    return res_josn_data.table_api(data=serializer.data, count=len(role_data))


@api_view(['POST'])
@jwt_login_required
def user_role_update(request):
    User.objects.filter(id_number=request.data['id_number']).update(**{'role_id': request.data['role_id']})
    exec_log(request, is_access=True, desc=request.data.dict())
    return res_josn_data.success_api(msg='角色更新成功')


class UserGenericView(ModelViewSetLayui):  # 用户视图
    queryset = User.objects.all()
    serializer_class = UserModelSerializer

    def create(self, request, *args, **kwargs):
        """
        重写create方法，密码字段需加密
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        post_data = request.data.dict()
        update_value = {
            'role': int(post_data['role']),
            'enable': int(post_data['enable'])
        }
        post_data.update(update_value)

        serializer = self.get_serializer(data=post_data)
        if serializer.is_valid(raise_exception=True):
            validated_data = serializer.validated_data
            validated_data['id_password'] = make_password(request.data['id_password'], salt=None, hasher='default')
            print(validated_data)
            serializer.save()
            exec_log(request, is_access=True, desc=post_data)
        return res_josn_data.success_api('用户添加成功')
